# -*- coding: utf-8 -*-
import bs4
import requests
import requests.utils
import pickle

import os
import time
import json
import random
import math
import re

import argparse

import sys

def tags_val(tag, key='', index=0):
    if len(tag) == 0 or len(tag) <= index:
        return ''
    elif key:
        txt = tag[index].get(key)
        return txt.strip(' \t\r\n') if txt else ''
    else:
        txt = tag[index].text
        return txt.strip(' \t\r\n') if txt else ''


class WPHWrapper(object):
    num = 1

    def __init__(self, usr_name=None, usr_pwd=None):
        print('请输入用户名：')
        self.usr_name = input()
        print('请输入经过MD5加密后的密码：')
        self.usr_pwd = input()
        print('请输入商品code:')
        self.good_cood = input()
        print('请输入商品id:')
        self.good_id = input()

        self.vipc = ''
        self.captcha = ''

        self.sess = requests.Session()

        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
            'ContentType': 'text/html; charset=utf-8',
            'Accept-Encoding': 'gzip, deflate, sdch',
            'Accept-Language': 'zh-CN,zh;q=0.8',
            'Connection': 'keep-alive',
        }

        self.cookies = {}

    def marsCreat(self, leng=32):
        t = math.ceil(time.time()*1000)
        x = "0123456789abcdef"
        tmp = ''
        for i in range(leng):
            r = math.ceil(random.random()*1E8) % len(x)
            tmp += x[r:r+1]

        return str(t) + "_" + tmp

    def getCaptcha(self):
        url = 'https://passport.vip.com/captcha/V2/getICaptcha'

        resp = self.sess.get(
            url,
            headers=self.headers,
            cookies=self.cookies,
            params={
                'type': 0,
                'vipc': self.vipc,
                'v': round(time.time() * 1000),
            }
        )

        image_file = 'vipc.png'
        with open(image_file, 'wb') as f:
            for chunk in resp.iter_content(chunk_size=1024):
                f.write(chunk)

        if os.name == 'nt':
            os.system('start ' + image_file)

    def CheckCaptcha(self):
        print('请输入验证码:')
        self.captcha = input()
        url = 'https://passport.vip.com/captcha/ajaxCheckCaptcha'

        resp = self.sess.post(
            url,
            headers=self.headers,
            cookies=self.cookies,
            params={
                'type': 0,
                'vipc': self.vipc,
                'anticache': round(time.time() * 1000),
                'captcha': self.captcha
            }
        )
        rs = json.loads(resp.text)

        if rs['errorCode'] == 200:
            print('验证码校验成功!!!')
            return True
        else:
            if rs['errorCode'] == 20203:
                print('验证码过期,重新获取验证码......')
                self.vipc = rs['vipc']
                self.getCaptcha()
                self.CheckCaptcha()
            if rs['errorCode'] == 0:
                print('验证码输入错误,请重新输入')
                self.CheckCaptcha()
            else:
                print('验证码校验不通过')
                return False

        return False

    def login(self):
        try:
            print('+++++++++++++++++++++++++++登陆准备+++++++++++++++++++++++++++')
            url = [
                'https://passport.vip.com/login',
            ]
            resp = self.sess.get(url[0], headers=self.headers)

            if resp.status_code != requests.codes.OK:
                print('获取登录页失败: %u' % resp.status_code)
                return False

            for k, v in resp.cookies.items():
                self.cookies[k] = v

            self.cookies['mars_cid'] = self.marsCreat()

            self.headers['Host'] = 'passport.vip.com'
            self.headers['Origin'] = 'https://passport.vip.com'
            self.headers['Referer'] = 'https://passport.vip.com/login'

            resp = self.sess.post(
                url[0],
                headers=self.headers,
                cookies=self.cookies,
                params={
                    'loginName': self.usr_name,
                    'password': self.usr_pwd,
                    'remUser': '1',
                    'vipc': '',
                    'captcha': '',
                    'anticache': round(time.time() * 1000),
                    'whereFrom': ''
                }
            )

            rs = json.loads(resp.text)
            data = rs['data']
            result = rs['result']
            self.vipc = data['vipc']

            if result == 'error':
                self.getCaptcha()

                if self.CheckCaptcha():
                    resp = self.sess.post(
                        url[0],
                        headers=self.headers,
                        cookies=self.cookies,
                        params={
                            'loginName': self.usr_name,
                            'password': self.usr_pwd,
                            'remUser': '1',
                            'vipc': self.vipc,
                            'captcha': self.captcha,
                            'anticache': round(time.time() * 1000),
                            'whereFrom': ''
                        }
                    )

                    for k, v in resp.cookies.items():
                        self.cookies[k] = v

                    result = json.loads(resp.text)
                    if result['result'] == 'success':
                        print('登陆成功-_-')
                        return True
                    else:
                        print('登陆失败')
                        return False

                else:
                    print('验证码校验不通过')
                    return False

        except Exception as e:
            print('Exp:', e)

    def buy(self):
        good_url = 'https://detail.vip.com/detail-' + \
            self.good_cood+'-'+self.good_id+'.html'
        url1 = 'https://detail.vip.com/detail-1710612760-6919016081299770264.html'
        self.headers['Host'] = 'detail.vip.com'
        self.headers['Origin'] = ''
        self.headers['Referer'] = good_url
        resp = self.sess.get(good_url)
        good_data = {
            'color': '',
            'price': '',
            'name': '',
        }

        soup = bs4.BeautifulSoup(resp.text, "html.parser")

        tags = soup.select('a.color-selected .color-item-name')
        good_data['color'] = tags_val(tags)

        tags = soup.select('span.pbox-price em')
        good_data['price'] = tags_val(tags)

        tags = soup.select('p.pib-title-detail')
        good_data['name'] = tags_val(tags)

        self.headers['Host'] = 'stock.vip.com'
        resp = self.sess.get(
            'https://stock.vip.com/detail',
            headers=self.headers,
            cookies=self.cookies,
            params={
                'callback': 'stock_detail',
                'merchandiseId': self.good_id,
                'is_old': 1,
                'areaId': '104104103',
                '_': round(time.time() * 1000),
            }
        )
        print('---------------------第' +
              str(WPHWrapper.num)+'次抢购---------------------')
        re_text = re.findall('^.*\((.*)\)', resp.text)
        result = json.loads(re_text[0])
        item = result['items']
        self.id = item[0]['id']
        if item[0]['stock'] == 0:
          print('库存为0，重新刷新')
          return False

        print(good_data)

        self.headers['Host'] = 'cart.vip.com'
        self.headers['Origin'] = ''
        self.headers['Referer'] = good_url
        resp = self.sess.get(
            'https://cart.vip.com/te2/add.php',
            headers=self.headers,
            cookies=self.cookies,
            params={
                'callback': 'jQuery110209780326408506119_' + str(round(time.time() * 1000)),
                'size_id': self.id,
                'num': 1,
                'act': '',
                'client_time': round(time.time()),
                'mars_cid': self.vipc,
                '_': round(time.time() * 1000),
            }
        )

        re_text = re.findall('^.*\((.*)\);$', resp.text)
        if len(re_text) != 0:
            obj = json.loads(re_text[0])
            print(obj)
            if obj['code'] == 200:
                return True
            else:
                if obj['code'] == 7001 or obj['code'] == 7002:
                    print(obj['msg'])
                    return False
                else:
                    print(obj['msg'])
                    return False
        else:
            print('解析json错误')
            return False

def main():
    wph = WPHWrapper()
    if not wph.login():
        return

    while not wph.buy():
        WPHWrapper.num += 1
        time.sleep(4000.0 / 1000.0)


if __name__ == '__main__':
    main()
